06. Sorting Collections
Sorting Collections
ND079 C1 L5 A03c Sorting Collection
The collections framework provides a sort
method that can be used to sort lists containing the following types of objects:
- Strings
- Wrapper objects
- User-defined classes
Let's have a look at the syntax for each of these.
Strings
A list of Strings can be sorted by simply passing the list to the Collections.sort()
method. In the example bellow, the names will be sorted in ascending order.
List<String> names = new LinkedList<String>();
names.add("Mike");
names.add("Bob");
names.add("Alice");
Collections.sort(names);
Wrapper Objects
Wrapper objects were introduced in Java to wrap primitive variable types into objects. In the example below, the primitive int
values are being converted to Integer
objects and then sorted.
List<Integer> numbers = new LinkedList<Integer>();
numbers.add(201);
numbers.add(100);
numbers.add(101);
Collections.sort(numbers);
User-Defined Classes
User-defined classes will need to implement the Comparable Interface in order to use the Collections.sort()
method. The Comparable Interface provides a method, compareTo
, which is used to compare two objects of the same type. In the example below we are using the Person object's name
field to compare Person objects. This line of code, name.compareTo(person.name)
, handles all of the hard work.
import java.util.*;
class Person implements Comparable<Person> {
public String name;
public Person(String name) {
this.name = name;
}
public int compareTo(Person person) {
return name.compareTo(person.name);
}
}
public class PersonSort {
public static void main(String[] args) {
ArrayList<Person> people = new ArrayList<Person>();
people.add(new Person("Same"));
people.add(new Person("Mike"));
people.add(new Person("Apple"));
Collections.sort(people);
for (Person person : people) {
System.out.println(person.name);
}
}
}
Note that it is up to us as the developers to select the variables we want to use when we compare two user-defined classes.